/*
 * "Hello World" example.
 *
 * This example prints 'Hello from Nios II' to the STDOUT stream. It runs on
 * the Nios II 'standard', 'full_featured', 'fast', and 'low_cost' example
 * designs. It runs with or without the MicroC/OS-II RTOS and requires a STDOUT
 * device in your system's hardware.
 * The memory footprint of this hosted application is ~69 kbytes by default
 * using the standard reference design.
 *
 * For a reduced footprint version of this template, and an explanation of how
 * to reduce the memory footprint for a given application, see the
 * "small_hello_world" template.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "system.h"
#include "altera_avalon_spi.h"
#include "altera_avalon_pio_regs.h"
#include "altera_avalon_timer_regs.h"
#include "altera_avalon_timer.h"
#include "sys/alt_irq.h"
#include "stdint.h"

#include "drivers/adc128s.h"

void timer_irq(void* base);
void pio_1_irq(void* base);

int main()
{
	printf("Hello from Nios II!\n");

	/* Register the interrupt */
	//alt_ic_isr_register(TIMER_IRQ_INTERRUPT_CONTROLLER_ID, TIMER_IRQ, timer_irq, (void*)0, (void*)0);
	//alt_ic_isr_register(PIO_1_IRQ_INTERRUPT_CONTROLLER_ID, PIO_1_IRQ, pio_1_irq, (void*)0, (void*)0);

	/* Enable interrupt */
	//IOWR_ALTERA_AVALON_PIO_IRQ_MASK(PIO_1_IRQ, 0xFF);

	/* Start timer */
	//IOWR_ALTERA_AVALON_TIMER_CONTROL(TIMER_BASE, ALTERA_AVALON_TIMER_CONTROL_ITO_MSK
	//| ALTERA_AVALON_TIMER_CONTROL_START_MSK);

	/* Stop timer */
	// IOWR_ALTERA_AVALON_TIMER_CONTROL (TIMER_BASE, ALTERA_AVALON_TIMER_CONTROL_STOP_MSK);

	uint8_t data;
	while(1)
	{
		data = IORD_ALTERA_AVALON_PIO_DATA(PIO_1_BASE);
		IOWR(SDRAM_CONTROLLER_BASE, 0, data);

		data = IORD(SDRAM_CONTROLLER_BASE, 0);
		IOWR_ALTERA_AVALON_PIO_CLEAR_BITS(PIO_0_BASE, data);
		IOWR_ALTERA_AVALON_PIO_SET_BITS(PIO_0_BASE, ~data);
	}

	return 0;
}


void timer_irq (void* base)
{
	/* Clear TO bit in status register */
	IOWR_ALTERA_AVALON_TIMER_STATUS(base, 0);

	/* Stop timer */
	// IOWR_ALTERA_AVALON_TIMER_CONTROL (TIMER_BASE, ALTERA_AVALON_TIMER_CONTROL_STOP_MSK);
}

void pio_1_irq(void* base)
{
	int data = IORD_ALTERA_AVALON_PIO_DATA(PIO_1_BASE);
}
